package com.yunquan.ohana.ui.verifyEmail

import android.app.Application
import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.binding.command.BindingConsumer
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.ToastUtils
import okhttp3.RequestBody.Companion.toRequestBody

class VerifyEmailViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    val mHandler = Handler(Looper.getMainLooper())

    val email = ObservableField<String>()
    val code = ObservableField<String>()

    val showError = ObservableField(false)
    val showTimer = ObservableField(true)

    var count = 60
    val countTime = ObservableField<String>()

    val onResendClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            if (countTime.get() == "0") {
                sendEmailCode()
            } else {
                ToastUtils.showShort(R.string.send_too_fast)
            }
        }
    })

    val onInputChangeClick = BindingCommand(object : BindingConsumer<String> {
        override fun call(t: String) {
            if (showError.get() == true && t.isNotEmpty()) {
                showError.set(false)
            }
            if (t.length == 6) {
                L.e("验证码：${t}")
                bindEmail(t)
            }
        }
    })

    private var countRun: Runnable? = null

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        countRun = Runnable {
            if (count > 0) {
                count--
                countTime.set(count.toString())
                mHandler.postDelayed(countRun!!, 1000)
                if (showTimer.get() == false) {
                    showTimer.set(true)
                }
            } else {
                if (showTimer.get() == true) {
                    showTimer.set(false)
                }
            }
        }
        mHandler.postDelayed(countRun!!, 1000)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        countRun?.let { mHandler.removeCallbacks(it) }
        super.onDestroy(owner)
    }

    private fun sendEmailCode() {
        val params = mutableMapOf<String, String>()
        params["email"] = email.get()!!
        val json = Gson().toJson(params)
        val body = json.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        showLoading()
        BaseHttp.api.sendEmailCode(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSuccess(result: Boolean?) {
                    if (result == true) {
                        count = 60
                        mHandler.postDelayed(countRun!!, 1000)
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    private fun bindEmail(code: String) {
        val params = mutableMapOf<String, String>()
        params["email"] = email.get()!!
        params["code"] = code
        val json = Gson().toJson(params)
        val body = json.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        showLoading()
        BaseHttp.api.bindEmail(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSuccess(result: Boolean?) {
                    if (result == true) {
                        RxBus.getDefault().post(EventEntity(EventType.UPDATE_EMAIL, email.get()))
                        finish()
                    } else {
                        showError.set(true)
                        this@VerifyEmailViewModel.code.set("")
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    showError.set(true)
                    this@VerifyEmailViewModel.code.set("")
                    ToastUtils.showShort(e.message ?: "Code Error")
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}